package com.tansun.easycare.rule.utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import com.tansun.easycare.rule.common.rulebasebean.Action;
import com.tansun.easycare.rule.common.rulebasebean.DThen;
import com.tansun.easycare.rule.common.rulebasebean.DWhen;
import com.tansun.easycare.rule.common.rulebasebean.Fact;
import com.tansun.easycare.rule.common.rulebasebean.RuleCollection;
import com.tansun.easycare.rule.common.rulebasebean.RuleItem;
import com.tansun.rule.model.toolbean.FunctionItem;
import com.tansun.rule.model.toolbean.RuleModel.RuleType;
import com.tansun.rule.utils.StringUtils;

public class DroolsUtils {

    private static SimpleDateFormat sdfzh = new SimpleDateFormat("yyyy-MM-dd");
    private static SimpleDateFormat sdfen = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);

    public static String convert2Drl(RuleCollection ruleCollection) throws Exception {

        String content = convert2DrlTxt(ruleCollection);
        //FileUtils.write(new File(ruleCollection.getSavePath()), content,"UTF-8");
        return content;

    }

    /**
     * 决策树drl函数模式
     * @param ruleCollection
     * @param ruletype
     * @return
     * @throws Exception
     */
    public static String convert2DrlFunc(RuleCollection ruleCollection,Set<String> initList,String ruletype,String isSingle) throws Exception {
    	//新增
    	String id = com.tansun.rule.utils.StringUtils.GenerateRandom(6);
    	String ruleName = ruletype+"_" + id ;
    	String modelCode = ruleCollection.getDrlName();
    	FunctionItem funcItem = getFunctionItem(ruletype, ruleCollection);
		RuleItem rule = new RuleItem();
		rule.setRuleName(ruleName);
		rule.setSalience(1);
		rule.getdThen().getListAction().add(new Action("	"+funcItem.getFunctionName()+"($insertMap,metaMap,ruleHelper,droolsRuleLog,drools);\r\n"));
		rule.setAddlog(0);

    	List<RuleItem> items = ruleCollection.getListItem();
    	List<RuleItem> newitems = new ArrayList<RuleItem>();
    	newitems.add(rule);
    	ruleCollection.setListItem(newitems);
    	ruleCollection.getDroolsImport().add("import org.drools.core.spi.KnowledgeHelper;");
		//用于存储互斥锁标记
		Map<String,List<String>> mutex2Var = new HashMap<String,List<String>>();
    	StringBuilder ifcode = new StringBuilder();
    	for(int i=0;i<items.size();i++) {
    		RuleItem ruleItem = items.get(i);
    		if( "on".equals(ruleItem.getEnabled()) || ruleItem.getEnabled() == null ){
	    		DWhen itemDWhen = ruleItem.getdWhen();
	        	Fact fact = itemDWhen.getFirstFact();
	        	List<Fact> facts = null;
	        	if( RuleCollection.RULESCORE.equals(ruletype) ) {
	        		facts = itemDWhen.getFactList();
	        	}else {
	        		facts = itemDWhen.getEvalList();
	        	}
	        	
	    		String ifcondition = "";
	    		if(fact!=null && StringUtils.isNotEmpty(fact.getContent())) {
	    			facts.add(0, fact);
	    		}
	    		if(facts!=null&& facts.size()>0) {
	    			ifcondition = facts2Condition(facts).replace("$insertMap", "dataMap");
	    		}
				
	    		//添加日期生效条件
	    		ifcondition = addDateCondition(ifcondition, ruleItem);
	    		
	        	DThen itemDThen = ruleItem.getdThen();
	        	List<Action> actions = itemDThen.getListAction();
	    		List<String> actionCodes = new ArrayList<String>();
	    		if(actions!=null&& actions.size()>0) {
	    			for(Action a:actions) {
	    				actionCodes.add(a.getContent().replace("$insertMap", "dataMap"));
	        		}
	    		}
	    		if( RuleCollection.RULETREE.equals(ruletype) ) {
	    			List<String> logsArr = itemDThen.getLogsArr();
	    			if( logsArr != null && logsArr.size()>0) {
	            		actionCodes.addAll(logsArr);
	    			}
	    			actionCodes.add(0,"droolsRuleLog.addLogs(\""+modelCode+"\",\""+ruletype+"\",\""+ruleCollection.getObjName()+"\", drools,\""+ruleItem.getRuleResultInfo()+"\");");
	    			if( StringUtils.isNotEmpty(ifcondition) ) {
	    				ifcode.append("		if( "+ifcondition+" ){\r\n");
	    				ifcode.append("			"+StringUtils.join(actionCodes,"\r\n			")+"\r\n");
	    				if("1".equals(isSingle)) {
	    					ifcode.append("			return;\r\n");
	    				}
	    				ifcode.append("		}\r\n");
	    			}else {
	    				ifcode.append("		"+StringUtils.join(actionCodes,"\r\n		")+"\r\n");
	    			}
	    		}else if(RuleCollection.SIMPLERULEGRP.equals(ruletype)) {
	    			if(i<items.size()-1) {
	    				List<String> logsArr = itemDThen.getLogsArr();
	                	if( logsArr != null && logsArr.size()>0) {
	                		actionCodes.addAll(logsArr);
	                	}else {
	                		actionCodes.add("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");");
	                	}
	    			}
	    			String mutex = ruleItem.getActivationGroup();
			    	if(StringUtils.isNotEmpty(mutex)) {
			    		String var = "res"+i;
			    		if(mutex2Var.containsKey(mutex)) {
			    			List<String> list = mutex2Var.get(mutex);
				    		ifcode.append("		//规则:").append(ruleItem.getRuleName()).append("\n");
							if( StringUtils.isNotEmpty(ifcondition) ) {
				    			ifcode.append("		boolean "+var+" = false;\n");
				    			ifcode.append("		if( !(").append(StringUtils.join(list," && ")).append(") ) {\n");
								ifcode.append("			if( ").append(ifcondition).append(" ){\n");
								ifcode.append("				").append(StringUtils.join(actionCodes,"\n				")).append("\n");
								ifcode.append("				").append(var).append(" = true;\n");
								ifcode.append("			}\n");
								ifcode.append("		}\n");
							}else {
								ifcode.append("		boolean ").append(var).append(" = true;\n");
								ifcode.append("		").append(StringUtils.join(actionCodes,"\n		")).append("\n");
							}
			    			list.add(var);
			    		}else {
			    			List<String> list = new ArrayList<String>();
			    			list.add(var);
			    			mutex2Var.put(mutex,list);
				    		ifcode.append("		//规则:").append(ruleItem.getRuleName()).append("\n");
							if( StringUtils.isNotEmpty(ifcondition) ) {
								ifcode.append("		boolean "+var+" = false;\n");
								ifcode.append("		if( ").append(ifcondition).append(" ){\n");
								ifcode.append("			").append(StringUtils.join(actionCodes,"\n			")).append("\n");
								ifcode.append("			").append(var).append(" = true;\n");
								ifcode.append("		}\n");
							}else {
								ifcode.append("		boolean "+var+" = true;\n");
								ifcode.append("		").append(StringUtils.join(actionCodes,"\n		")).append("\n");
							}
			    		}    		
			    	}else {
			    		ifcode.append("		//规则:").append(ruleItem.getRuleName()).append("\n");
						if( StringUtils.isNotEmpty(ifcondition) ) {
							ifcode.append("		if( ").append(ifcondition).append(" ){\n");
							ifcode.append("			").append(StringUtils.join(actionCodes,"\n			")).append("\n");
							ifcode.append("		}\n");
						}else {
							ifcode.append("		").append(StringUtils.join(actionCodes,"\n		")).append("\n");
						}
			    	}
	    		}else if ( RuleCollection.POLIRULEGRP.equals(ruletype) || RuleCollection.RULETABLE.equals(ruletype) ) {
	    			if(i<items.size()-1) {
	    				List<String> logsArr = itemDThen.getLogsArr();
	                	if( logsArr != null && logsArr.size()>0) {
	                		actionCodes.addAll(logsArr);
	                	}else {
	                		actionCodes.add("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");");
	                	}
	    			}
	    			if( StringUtils.isNotEmpty(ifcondition) ) {
		    			ifcode.append("	if( " + ifcondition + " ){\r\n");
						ifcode.append("		"+StringUtils.join(actionCodes,"\r\n		")+"\r\n");
	    				if("1".equals(isSingle)) {
	    					ifcode.append("			return;\n");
	    				}
						ifcode.append("	}\n");
	    			}else {
	    				ifcode.append("	"+StringUtils.join(actionCodes,"\r\n	")+"\r\n");
	    			}
	    		}else if( RuleCollection.RULESCORE.equals(ruletype) ) {
	    			if( itemDThen.getRuleContent().indexOf("scoreCardObj.addCardItem") >= 0 ) {
	    				itemDThen.getLogsArr().addAll(actionCodes);
	    				actionCodes = itemDThen.getLogsArr();
	                    String rc = itemDThen.getRuleContent().trim();
	                    String param = rc.replaceFirst("scoreCardObj.addCardItem\\(", "").replaceFirst("\\);", "");
	                    String logparam = param.substring(0, param.lastIndexOf("\",") + 2) + "\"" + param.substring(param.lastIndexOf("\",") + 2, param.length()).replace("\"", "").replace(",", "\",\"") + "\"";
	                    actionCodes.add(0,"droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools, " + logparam + ");\n");
	    			}else {
	    				//actionCodes.add(0,"droolsRuleLog.addLogs(\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");");
	    			}
	    			String actionStr = StringUtils.join(actionCodes,"\r\n		");
	    			if( StringUtils.isNotEmpty(ifcondition) ) {
	    				ifcode.append("		if( "+ifcondition+" ){\r\n");
	    				ifcode.append("			"+actionStr+"\r\n");
	    				if("1".equals(isSingle)) {
	    					ifcode.append("			return;\r\n");
	    				}
	    				ifcode.append("		}\r\n");
	    			}else {
	    				if(actionStr.contains("\"其他\");")) {
	    					ifcode.append("else{\n");
	    					ifcode.append("			"+actionStr+"\r\n");
	    					ifcode.append("		}\r\n");
	    				}else {
	    					ifcode.append("		"+actionStr+"\r\n");
	    				}
	    			}
	    		}
	    		if(ifcode.length() > 100000) {//不要超过25万
	    			FunctionItem funcItemNext = getFunctionItem(ruletype, ruleCollection);
	    			ifcode.append("	"+funcItemNext.getFunctionName()+"(dataMap,metaMap,ruleHelper,droolsRuleLog,drools);\r\n");
	    			funcItem.setFunctionBody(ifcode.toString());
	    			funcItem = funcItemNext;
	    			ifcode.delete(0, ifcode.length()); 
	    		}
    		}
    	}

    	funcItem.setFunctionBody(ifcode.toString());
    	
        String content = convert2DrlTxt(ruleCollection, initList);
        //FileUtils.write(new File(ruleCollection.getSavePath()), content,"UTF-8");
        return content;

    }
    
    public static FunctionItem getFunctionItem(String ruletype,RuleCollection ruleCollection) {
    	FunctionItem funcItem = new FunctionItem(); 
    	funcItem.setReturnType("void");
    	funcItem.setFunctionName(ruletype+"_func_"+com.tansun.rule.utils.StringUtils.GenerateRandom(6));
    	funcItem.setParams(new ArrayList<String[]>());
    	funcItem.getParams().add(new String[] {"Map","dataMap"});
    	funcItem.getParams().add(new String[] {"Map","metaMap"});
    	funcItem.getParams().add(new String[] {"RuleHelper","ruleHelper"});
    	funcItem.getParams().add(new String[] {"DroolsRuleLog","droolsRuleLog"});
    	funcItem.getParams().add(new String[] {"KnowledgeHelper","drools"});
    	ruleCollection.getFuncList().add(funcItem);
    	return funcItem;
    }
    /**
     * 规则集对象转换drl文本
     */
    public static String convert2DrlTxt(RuleCollection ruleCollection,Set<String> initList) throws Exception {


        if (ruleCollection == null) {
            return null;
        }
        ruleCollection.setDroolsDialect("dialect \"mvel\"");
        ruleCollection.getDroolsImport().add("import java.util.*;");
        ruleCollection.getDroolsImport().add("import com.tansun.rule.utils.*;");
        ruleCollection.getDroolsGlobal().add("global RuleHelper ruleHelper;");
        ruleCollection.getDroolsGlobal().add("global DroolsRuleLog droolsRuleLog;");
        ruleCollection.getDroolsGlobal().add("global java.util.Map metaMap;");
        ruleCollection.getDroolsGlobal().add("global java.util.Map dataMap;");
        if (ruleCollection.getContentType() != null) {
//            ruleCollection.setDroolsPackageHeader("package com.tansun." + ruleCollection.getContentType());
        	ruleCollection.setDroolsPackageHeader("package com.tansun.policyrulegroup");
        }

        if (ruleCollection.getRuleflowGroup() == null) {
//            ruleCollection.setRuleflowGroup(ruleCollection.getDrlName() + "_" + ruleCollection.getVersion());
        	ruleCollection.setRuleflowGroup(ruleCollection.getDrlName());
        }


        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append(ruleCollection.getDroolsPackageHeader() + "\n");
        for (String importstr : ruleCollection.getDroolsImport()) {
            strBuffer.append(importstr + "\n");
        }
        for (String global : ruleCollection.getDroolsGlobal()) {
            strBuffer.append(global + "\n");
        }


        strBuffer.append(ruleCollection.getDroolsDialect() + "\n");
        strBuffer.append("ruleflow-group \"" + ruleCollection.getRuleflowGroup() + "\"\n");

        for (int i = 0; i < ruleCollection.getListItem().size(); i++) {
            RuleItem ruleItem = ruleCollection.getListItem().get(i);
            String itemtxt = convertRuleItem2DrlTxt(ruleItem, ruleCollection);
            strBuffer.append(itemtxt);
        }
        List<FunctionItem> funcList = ruleCollection.getFuncList();
        if(funcList!=null) {
	        for(FunctionItem functionItem:funcList) {
	        	String functionItemTxt = convertFuncItem2DrlTxt(functionItem);
	        	strBuffer.append(functionItemTxt);
	        }
        }
        String updateInsertMap = "\n"
                + "rule \"updateInsertMap_" + ruleCollection.getRuleflowGroup()+ "\"\n"
                + "salience 2147483647\n"
                + "no-loop true\n"
                + "when\n"
                + "   $insertMap : Map()\n"
                + "then\n";
        if(initList!=null) {
	        for(String line:initList) {
	        	updateInsertMap += "   "+line+"\n";
	        }
        }
        updateInsertMap = updateInsertMap
                + "   update($insertMap);\n"
                + "end\n";
        strBuffer.append(updateInsertMap);
        
        return strBuffer.toString();
    }

    /**
     * 规则集对象转换drl文本
     */
    public static String convert2DrlTxt(RuleCollection ruleCollection) throws Exception {
		return convert2DrlTxt(ruleCollection,null);
    }
    /**
     * 规则对象转换文本
     */
    public static String convertRuleItem2DrlTxt(RuleItem ruleItem, RuleCollection ruleCollection) throws Exception {
    	String modelCode = ruleCollection.getDrlName();
        StringBuffer strBuffer = new StringBuffer();
        //RuleItem ruleItem = ruleCollection.getListItem().get(i); +StringUtils.generateShortUuid()
        if (RuleType.policyrulegroup.toString().equals(ruleCollection.getContentType())
        		||RuleCollection.RULETREE.toString().equals(ruleCollection.getContentType())){
        	ruleItem.setRuleName("U"+StringUtils.generateTenUuid()+"_"+ruleItem.getRuleName());
        }
        strBuffer.append("rule \"" + ruleCollection.getDrlName() + ruleCollection.getVersion() + "_" + ruleItem.getRuleName() + "\"\n");

        //规则集 决策树
        if (RuleCollection.RULEGRP.equals(ruleCollection.getContentType())
                || RuleCollection.EXCLUSIONS.equals(ruleCollection.getContentType())) {
            //String getActivationGroup =  ruleCollection.getDrlName()+StringUtils.generateShortUuid();
            strBuffer.append("activation-group \"" + ruleCollection.getDrlName() + "\"\n");
        } else if (RuleCollection.RULESCORE.equals(ruleCollection.getContentType())) {
            if (StringUtils.isNoneBlank(ruleItem.getActivationGroup())) {
                strBuffer.append("activation-group \"" + ruleItem.getActivationGroup() + "\"\n");
            }
            //政策规则集
        } else {
            //互斥组名
            if (StringUtils.isNotBlank(ruleItem.getActivationGroup())) {
                strBuffer.append("activation-group \"" + ruleItem.getActivationGroup() + "\"\n");
            }
        }

        //开始日期
        if (StringUtils.isNotBlank(ruleItem.getDateEffective())) {
            //"2015-11-24" to "24-Nov-2015"
            strBuffer.append("date-effective \"" + sdfen.format(sdfzh.parse(ruleItem.getDateEffective())) + "\"\n");
        }
        //结束日期
        if (StringUtils.isNotBlank(ruleItem.getDateExpires())) {
            strBuffer.append("date-expires \"" + sdfen.format(sdfzh.parse(ruleItem.getDateExpires())) + "\"\n");
        }
        //优先集
        strBuffer.append("salience " + ruleItem.getSalience() + "\n");
        //是否有效 true false
        if (StringUtils.isNotBlank(ruleItem.getEnabled())) {
            strBuffer.append("enabled " + ("on".equals(ruleItem.getEnabled()) ? "true" : "false") + "\n");
        }
        if ("simpleTxt".equals(ruleItem.getTxtType())) {
            strBuffer.append(ruleItem.getComment() + "\n");
            //一个规则结束
            strBuffer.append("end\n\n\n");
            return strBuffer.toString();
        }
        //when
        DWhen when = ruleItem.getdWhen();
        strBuffer.append("when\n");
        strBuffer.append(when.getRuleContent() + "\n");
        //then
        DThen then = ruleItem.getdThen();
        strBuffer.append("then\n");
        //有些辅助型规则不要日志记录
        if (then.getRuleContent().indexOf("droolsRuleLog.addLogs") < 0 && ruleItem.getAddlog() == 1) {
            //评分卡
            if (RuleCollection.RULESCORE.equals(ruleCollection.getContentType()) && then.getRuleContent().indexOf("scoreCardObj.addCardItem") >= 0) {
                //scoreCardObj.addCardItem("无",2,-42);
                String rc = then.getRuleContent().trim();
                String param = rc.replaceFirst("scoreCardObj.addCardItem\\(", "").replaceFirst("\\);", "");
                String[] arrParam = param.split(",Double\\.parseDouble\\(");
                String logparam = "";
                for(int i=0;i<arrParam.length;i++) {
                	String paramStr = arrParam[i];
                	if(i>0) {
                		paramStr = "Double.parseDouble("+paramStr;
                		paramStr = ",\""+paramStr.replace("\"", "\\\"")+"\"";
                		logparam += paramStr;
                	}else {
                		String[] eachArr = paramStr.split(",");
                		List<String> addArr = new ArrayList<>(); 
                		for(String each:eachArr) {
                			if(each.startsWith("\"")) {
                				addArr.add(each);
                			}else {
                				addArr.add("\""+each+"\"");
                			}
                		}
                		logparam += StringUtils.join(addArr,",");
                	}
                }
                strBuffer.append("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools, " + logparam + ");\n");
                //决策树
            } else if (RuleCollection.RULETREE.equals(ruleCollection.getContentType())) {
                strBuffer.append("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");\n");
                //策略树
            } else if (RuleCollection.POLICYTREE.equals(ruleCollection.getContentType())) {
                String rc = then.getRuleContent().trim();
                String leafNo = rc.substring(rc.indexOf("//leafNo:"), rc.length()).replace("//leafNo:", "");
                //leafNo
                String no = leafNo.substring(leafNo.indexOf("(") + 1, leafNo.indexOf(")"));

                strBuffer.append("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools, " + no + ");\n");
                //其他
            } else {
            	List<String> logsArr = then.getLogsArr();
                if( logsArr != null && logsArr.size()>0) {
                	for(String logStr:logsArr) {
                		strBuffer.append(logStr+"\n");
                	}
            	}else {
            		strBuffer.append("droolsRuleLog.addLogs(\""+modelCode+"\",\"" + ruleCollection.getContentType() + "\",\"" + ruleCollection.getObjName() + "\", drools,\""+ruleItem.getRuleResultInfo()+"\");\n");
            	}
            }

        }
        strBuffer.append(then.getRuleContent() + "\n");
        //一个规则结束
        strBuffer.append("end\n\n\n");
        strBuffer.append("//备注:" + ruleItem.getComment() + "\n");
        return strBuffer.toString();
    }

    /**
     * 规则函数对象转换文本
     */
    public static String convertFuncItem2DrlTxt(FunctionItem functionItem) throws Exception {
    	//函数名，返回类型，参数,函数体
    	String funcName = functionItem.getFunctionName();
    	String returnType = functionItem.getReturnType();
    	List<String[]> params = functionItem.getParams();
    	String funcBody = functionItem.getFunctionBody();
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append("function "+returnType+" "+funcName+"(");
        for(int i=0;i<params.size();i++) {
        	String[] typeParams = params.get(i);
        	strBuffer.append(typeParams[0]+" "+typeParams[1]);
        	if(i<params.size()-1) {
        		strBuffer.append(",");
        	}
        }
        strBuffer.append("){\n");
        strBuffer.append(funcBody);
        strBuffer.append("}\n");
        return strBuffer.toString();
    }
    
    /**
     * 将fact列表转为条件
     */
    public static String facts2Condition(List<Fact> facts) {
    	StringBuffer ifcondition = new StringBuffer();
    	for(int j=0;j<facts.size();j++) {
			Fact f = facts.get(j);
			String condStr = f.getContent();
			if( StringUtils.isNotEmpty(condStr) ) {
				if(condStr.endsWith("\n"))condStr = condStr.substring(0, condStr.length()-2);
				String suffix = f.getLineSuffix();//后缀
				String prefix = f.getLinePrefix();//前缀
    			if(StringUtils.isEmpty(suffix) && StringUtils.isEmpty(prefix)) {
    				if(j!=0 && j==facts.size()-1) {
    					ifcondition.append("\t\t(").append(condStr).append(")");
    				}else if(j==0 && j==facts.size()-1){
    					ifcondition.append("(").append(condStr).append(")");
    				}else if(j==0 && j!=facts.size()-1){
    					ifcondition.append("(").append(condStr).append(") &&\n");
    				}else {
    					ifcondition.append("\t\t(").append(condStr).append(") &&\n");
    				}
            	}else{
            		if( j<facts.size()-1 && (  (!suffix.contains("&") && !suffix.contains("|")) || f.getType() != facts.get(j+1).getType()  )  ) {
            			suffix += " && ";
            		}
    				if(j!=0 && j==facts.size()-1) {
    					ifcondition.append("\t\t").append(prefix ).append(condStr).append(suffix);
    				}else if(j==0 && j==facts.size()-1){
    					ifcondition.append(prefix ).append(condStr).append(suffix);
    				}else if(j==0 && j!=facts.size()-1){
    					ifcondition.append(prefix ).append(condStr).append(suffix).append("\n");
    				}else {
    					ifcondition.append("\t\t").append(prefix).append(condStr).append(suffix).append("\n");
    				}
            	}
			}
		}
		return ifcondition.toString();
    }
    
    /**
     * 获取添加日期条件
     */
    public static String addDateCondition(String ifcondition,RuleItem ruleItem) {
		String dateEffective = ruleItem.getDateEffective();	// 规则开始生效日期
		String dateExpires = ruleItem.getDateExpires();	// 规则过期日期
		String dateCondition = null;//日期条件
		if(StringUtils.isNotEmpty(dateEffective) && StringUtils.isNotEmpty(dateExpires)) {
			dateCondition = "(\""+dateEffective+"\".compareTo(RFDate.getDate()) <= 0 && \""+dateExpires+"\".compareTo(RFDate.getDate()) > 0 )";
		}else if(StringUtils.isNotEmpty(dateEffective) && StringUtils.isEmpty(dateExpires)) {
			dateCondition = "(\""+dateEffective+"\".compareTo(RFDate.getDate())) <= 0)";
		}else if(StringUtils.isEmpty(dateEffective) && StringUtils.isNotEmpty(dateExpires)) {
			dateCondition = "(\""+dateExpires+"\".compareTo(RFDate.getDate())) > 0)";
		}
		if( StringUtils.isNotEmpty(ifcondition) && StringUtils.isNotEmpty(dateCondition)) {
			ifcondition = dateCondition + " && (" + ifcondition + ")";
		}else if( StringUtils.isEmpty(ifcondition) && StringUtils.isNotEmpty(dateCondition)) {
			ifcondition = dateCondition;
		}
		return ifcondition;
    }
}
